package com.cdd.framework.security.filter;

import com.cdd.common.core.domain.model.BaseLoginUser;
import com.cdd.common.core.domain.model.LoginUser;
import com.cdd.common.utils.SecurityUtils;
import com.cdd.common.utils.StringUtils;
import com.cdd.framework.oauth2.domain.dto.ClientCacheObj;
import com.cdd.framework.oauth2.enums.LoginType;
import com.cdd.framework.web.service.SysTokenService;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * token过滤器 验证token有效性
 *
 * @author lc
 */
@Log4j2
@Component
public class TokenFilter extends OncePerRequestFilter
{

    @Resource
    private SysTokenService sysTokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        log.info("request------>{}", request.getRequestURI());
        String token = sysTokenService.getHeaderToken(request);
        if (StringUtils.isNotEmpty(token) && sysTokenService.hasSysTokenCache(token)) {
            BaseLoginUser loginUser = sysTokenService.getAccessTokenFromCache(token);
            if (loginUser != null) {
                this.buildAuthentication(request, loginUser.getLoginType());
            }
        }
        chain.doFilter(request, response);
    }

    private void buildAuthentication(HttpServletRequest request, String loginTypeStr) {
        LoginType loginType = LoginType.getTarget(loginTypeStr);
        Assert.notNull(loginType, "登录类型不正确");
        if (loginType == LoginType.SYS) {
            LoginUser loginUser = sysTokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
                SecurityContextHolder.getContext().setAuthentication(this.buildAuthentication(loginUser, request));
            }
        } else {
            ClientCacheObj cacheObj = sysTokenService.getLoginClient();
            if (StringUtils.isNotNull(cacheObj)) {
                SecurityContextHolder.getContext().setAuthentication(this.buildAuthentication(cacheObj, request));
            }
        }
    }

    private Authentication buildAuthentication(Object o, HttpServletRequest request) {
        // 创建 UsernamePasswordAuthenticationToken 对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                o, null, Collections.emptyList());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        return authenticationToken;
    }
}
